﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AxMSTSCLib;
using FD.RemoteAssistant.Core;
using FD.RemoteAssistant.Core.Extensions;
using FD.RemoteAssistant.Entities;
using FD.RemoteAssistant.Entities.Extensions;
using FDRemoteAssistant2.Extensions;
using FDRemoteAssistant2.Manager;
using FDRemoteAssistant2.Models;
using Sunisoft.IrisSkin;

namespace FDRemoteAssistant2
{
    /*
     * CreatedOn: 2018-05-15
     * CreatedBy: Jackie Lee(天宇遊龍)
     */
    public partial class FormMain : Form
    {
        #region  初始化
        public FormMain()
        {
            InitializeComponent();
            Init();
            se = new SkinEngine();
            se.SkinAllForm = true;
            //se.SkinDialogs = false;
            se.SkinFile = @"Vista2_color1.ssk";
        }

        private SkinEngine se;

        //private AxMsRdpClient9 client;
        private void Init()
        {
            ShowTitle(true);
            tabControl1.TabPages.Clear();
            SizeChanged += FormMain_SizeChanged;
            FormClosing += FormMain_FormClosing;
            WindowState = FormWindowState.Maximized;
            tabControl1.DoubleClick += TabControl1_DoubleClick;
            tabControl1.SelectedIndexChanged += TabControl1_SelectedIndexChanged;
            tsmiDisconnectAll.Enabled = false;
            FDHelper.Current.MenuDataChanged += Current_MenuDataChanged;

            foreach (var rs in RuntimeContext.Current.RemoteSettings.Where(s => s.IsEnable))
            {
                AddToMenu(rs, AddToMenuItemType.Add);
            }
        }
        #endregion

        #region 业务逻辑
        private void ShowTitle(bool pOnly = false)
        {
            if (pOnly || tabControl1.SelectedTab == null)
                Text = Application.ProductName;
            else
                Text = $"{ tabControl1.SelectedTab.Text} ({tabControl1.SelectedTab.ToolTipText}) - {Application.ProductName}";
        }

        private void Connect(IRemoteSetting remoteSetting, AddToMenuItemType addType = AddToMenuItemType.Remove, bool isFromAdd = false)
        {
            RemoteClientPage remoteClientPage = new RemoteClientPage(remoteSetting);
            tabControl1.TabPages.Add(remoteClientPage);
            tabControl1.SelectedTab = remoteClientPage;
            if (!isFromAdd)
            {
                AddToMenu(remoteSetting, addType); // 已改为事件添加
            }
            if (RuntimeContext.Current.AddSetting(remoteSetting))
            {
                FDHelper.Current.Save();
            }
            remoteClientPage.Connected = (sender, e) =>
            {
                ShowTitle();
                EnableMenuItem(tsmiConnect, FDHelper.Current.GetDisplayText(remoteSetting), false);
            };
            remoteClientPage.Disconnected = (sender, rsInfo) =>
            {
                Disconnect(FDHelper.Current.GetDisplayText(rsInfo));
            };
            remoteClientPage.Connect();
        }

        private void AddToMenu(IRemoteSetting remoteSetting, AddToMenuItemType type)
        {
            ToolStripMenuItem item;
            if (type.IsSpecifiedType(AddToMenuItemType.Add))
            {
                item = new ToolStripMenuItem(FDHelper.Current.GetDisplayText(remoteSetting));
                item.ToolTipText = FDHelper.Current.GetRemoteName(remoteSetting, true);
                tsmiConnect.DropDownItems.Add(item);
                item.Click += ItemConnect_Click;
            }

            if (type.IsSpecifiedType(AddToMenuItemType.Remove))
            {
                item = new ToolStripMenuItem(FDHelper.Current.GetDisplayText(remoteSetting));
                item.ToolTipText = FDHelper.Current.GetRemoteName(remoteSetting, true);
                tsmiDisconnect.DropDownItems.Add(item);
                item.Click += ItemDisconnect_Click;
            }
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="name"></param>
        private void Disconnect(string name)
        {
            RemoveFromMenu(name);
            for (var i = 0; i < tabControl1.TabPages.Count; ++i)
            {
                RemoteClientPage page = (RemoteClientPage)tabControl1.TabPages[i];
                if (page.Text.IgnoreCaseEquals(name))
                {
                    page.Disconnect();
                    tabControl1.TabPages.Remove(page);
                    page.Dispose();
                    GC.Collect();
                    break;
                }
            }
            ShowTitle(true);
            CheckDisconnectAllStatus();
            EnableMenuItem(tsmiConnect, name, true);
        }

        /// <summary>
        /// 服务器
        /// </summary>
        /// <param name="showName">显示的名称</param>
        /// <param name="valueText">真正值</param>
        private void ConnectToServer(string showName, string valueText)
        {
            var page = GetPage(showName);
            if (page != null)
            {
                tabControl1.SelectedTab = page;
                return;
            }
            var name = FDHelper.Current.GetServer(valueText);

            var rs = RuntimeContext.Current.FirstOrDefault(a => a.Server == name);
            if (rs == null)
            {
                this.MsgBox("不存在所选择的连接信息");
                return;
            }
            Connect(rs);
            CheckDisconnectAllStatus();
        }

        /// <summary>
        /// 获取Tab页
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private RemoteClientPage GetPage(string name)
        {
            foreach (RemoteClientPage page in tabControl1.TabPages)
            {
                if (page.Text.IgnoreCaseEquals(name))
                {
                    return page;
                }
            }

            return null;
        }

        /// <summary>
        /// 移除菜单项
        /// </summary>
        /// <param name="name"></param>
        private void RemoveFromMenu(string name)
        {
            RemoveItem(tsmiDisconnect, name);
        }

        private void RemoveItem(ToolStripMenuItem parentItem, string name)
        {
            //for (var i = 0; i < parentItem.DropDownItems.Count; ++i)
            //{
            //    var item = parentItem.DropDownItems[i];
            //    if (item.Text.IgnoreCaseEquals(name))
            //    {
            //        parentItem.DropDownItems.Remove(item);
            //        break;
            //    }
            //}
            HasItem(parentItem, name, item => { parentItem.DropDownItems.Remove(item); });
        }

        /// <summary>
        /// 是否存在菜单
        /// </summary>
        /// <param name="parentItem">父菜单项</param>
        /// <param name="name">菜单名</param>
        /// <param name="action4ItemHas">如果存在，则触发该操作</param>
        /// <returns></returns>
        private bool HasItem(ToolStripMenuItem parentItem, string name, Action<ToolStripItem> action4ItemHas = null)
        {
            for (var i = 0; i < parentItem.DropDownItems.Count; ++i)
            {
                var item = parentItem.DropDownItems[i];
                if (item.Text.IgnoreCaseEquals(name))
                {
                    action4ItemHas?.Invoke(item);
                    return true;
                }
            }

            return false;
        }

        private void ModifyItem(ToolStripMenuItem parentItem, string name, IRemoteSetting remoteSetting)
        {
            var newName = FDHelper.Current.GetDisplayText(remoteSetting);
            //for (var i = 0; i < parentItem.DropDownItems.Count; ++i)
            //{
            //    var item = parentItem.DropDownItems[i];
            //    if (item.Text.IgnoreCaseEquals(name))
            //    {
            //        item.Text = newName;
            //        item.ToolTipText = FDHelper.Current.GetRemoteName(remoteSetting, true);
            //        break;
            //    }
            //}
            HasItem(parentItem, name, item =>
            {
                item.Text = newName;
                item.ToolTipText = FDHelper.Current.GetRemoteName(remoteSetting, true);
            });
            var page = GetPage(name);
            if (page != null)
            {
                page.Text = newName;
                ShowTitle();
            }
        }

        private void EnableMenuItem(ToolStripMenuItem parentItem, string name, bool isEnable)
        {
            //for (var i = 0; i < parentItem.DropDownItems.Count; ++i)
            //{
            //    var item = parentItem.DropDownItems[i];
            //    if (item.Text.IgnoreCaseEquals(name))
            //    {
            //        item.Enabled = isEnable;
            //        break;
            //    }
            //}
            HasItem(parentItem, name, item => { item.Enabled = isEnable; });
        }

        private void CheckDisconnectAllStatus()
        {
            tsmiDisconnectAll.Enabled = tsmiDisconnect.DropDownItems.Count > 0;
        }

        /// <summary>
        /// 去除失效的
        /// </summary>
        /// <param name="remoteSetting"></param>
        private void DisableItem(IRemoteSetting remoteSetting)
        {
            if (remoteSetting.IsEnable)
            {
                if (!HasItem(tsmiConnect, remoteSetting.Name))
                {
                    AddToMenu(remoteSetting, AddToMenuItemType.Add);
                }
                //if (!HasItem(tsmiDisconnect, remoteSetting.Name))
                //{
                //    AddToMenu(remoteSetting, AddToMenuItemType.Remove);
                //}
            }
            else
            {
                RemoveItem(tsmiConnect, FDHelper.Current.GetDisplayText(remoteSetting));
            }
        }
        #endregion

        #region 事件处理
        #region 窗体事件
        private void FormMain_SizeChanged(object sender, EventArgs e)
        {
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (tabControl1.TabPages.Count > 0)
            {
                if (DialogResult.OK != this.MsgBox($"关闭当前窗口会结束所有已连接远程（{tabControl1.TabPages.Count}），是否确定关闭？",
                        MessageBoxButtons.OKCancel))
                {
                    e.Cancel = true;
                }
            }
        }

        private void Current_MenuDataChanged(object sender, MenuDataChangedArgs e)
        {
            switch (e.ChangeType)
            {
                case ChangeType.DataAdd:
                    AddToMenu(e.RemoteSetting, AddToMenuItemType.Both);
                    break;
                case ChangeType.DataModify:
                    ModifyItem(tsmiConnect, e.OldMenuName, e.RemoteSetting);
                    ModifyItem(tsmiDisconnect, e.OldMenuName, e.RemoteSetting);
                    DisableItem(e.RemoteSetting);
                    break;
                case ChangeType.DataRemove:
                    RemoveItem(tsmiConnect, FDHelper.Current.GetDisplayText(e.RemoteSetting));
                    RemoveItem(tsmiDisconnect, FDHelper.Current.GetDisplayText(e.RemoteSetting));
                    break;
            }
        }
        #endregion

        #region Tab控件事件
        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowTitle();
        }

        private void TabControl1_DoubleClick(object sender, EventArgs e)
        {
            RemoteClientPage page = (RemoteClientPage)tabControl1.SelectedTab;
            page.IsFullScreen = true;
        }
        #endregion

        #region 菜单事件
        private void tsmiNew_Click(object sender, EventArgs e)
        {
            using (var fs = new FormSettings())
            {
                if (DialogResult.OK == fs.ShowDialog())
                {
                    Connect(fs.Result, AddToMenuItemType.Both, true);
                }
            }
        }

        private void ItemDisconnect_Click(object sender, EventArgs e)
        {
            var item = (ToolStripMenuItem)sender;
            Disconnect(item.Text);
        }

        private void ItemConnect_Click(object sender, EventArgs e)
        {
            var item = (ToolStripMenuItem)sender;

            ConnectToServer(item.Text, item.ToolTipText);
        }

        private void tsmiConnect_Click(object sender, EventArgs e)
        {
        }

        private void tsmiDisconnect_Click(object sender, EventArgs e)
        {
        }

        private void tsmiDisconnectAll_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK != this.MsgBox("断开全部连接操作会断开所有已连接的服务器，是否继续？", MessageBoxButtons.OKCancel))
            {
                return;
            }
            for (int i = 0; i < tsmiDisconnect.DropDownItems.Count; ++i)
            {
                var item = tsmiDisconnect.DropDownItems[i];
                Disconnect(item.Text);
                i--;
            }

            CheckDisconnectAllStatus();
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            if (_aboutBoxLee == null)
            {
                _aboutBoxLee = new AboutBoxLee();
            }

            _aboutBoxLee.ShowDialog();
        }

        private AboutBoxLee _aboutBoxLee;
        private FormSettingList _formSettingList;

        private void tsmiConnectToAll_Click(object sender, EventArgs e)
        {
            foreach (var remoteSetting in RuntimeContext.Current.RemoteSettings)
            {
                Connect(remoteSetting);
            }
            CheckDisconnectAllStatus();
        }

        private void tsmiEditSettings_Click(object sender, EventArgs e)
        {
            if (_formSettingList == null)
            {
                _formSettingList = new FormSettingList((dispName, valueText) =>
                {
                    ConnectToServer(dispName, valueText);
                }, (rs, type) =>
                {
                    Connect(rs, type);
                });
            }

            _formSettingList.ShowDialog();
        }
        #endregion
        #endregion
    }
}

